package com.leyou.item.controller;

import com.leyou.common.dto.BrandDTO;
import com.leyou.common.vo.PageResult;
import com.leyou.item.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RefreshScope
@RestController
@RequestMapping("/brand")
public class BrandController {


    @Value("${sms.addr}")
    private String addr;

    @Autowired
    private BrandService brandService;

    @GetMapping("/getAddr")
    public String getAddr(){
        return addr;
    }


    /**
     * controller只用来传参数,返回参数
     * 一个处理器只调用一个service(事务传播行为) ?
     * required = false 意思是这个值不是必须要传入的
     * @param page
     * @param rows
     * @param key
     * @param sortBy
     * @param desc
     * @return
     */
    @GetMapping("/page")  //@RequestMapping之前用了这么久,难道也行,(好像确实也行.........总感觉有什么问题呢)
    public ResponseEntity<PageResult<BrandDTO>> pageQuery(@RequestParam(value = "page",defaultValue = "1") Integer page,
                                                          @RequestParam(value = "rows",defaultValue = "5") Integer rows,
                                                          @RequestParam(value = "key",required = false) String key,
                                                          @RequestParam(value = "sortBy",required = false) String sortBy,
                                                          @RequestParam(value = "desc",defaultValue = "false") Boolean desc){
        return ResponseEntity.ok(brandService.pageQuery(page,rows,key,sortBy,desc));
    }

    /**
     * BrandDTO接收前端返回的数据,因为是表单形式,所以不需要@ResquestBody
     * list集合中存的都是long类型的cid 例如:76 78 单个的
     * @RequestParam用来将前端接收的字符串类型cids转成list 集合类型的cids
     * @param brandDTO
     * @param cids
     * @return
     */
    @PostMapping
    public ResponseEntity<Void> saveBrand(BrandDTO brandDTO, @RequestParam("cids") List<Long> cids){
        brandService.saveBrand(brandDTO,cids);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    @GetMapping("/{id}")
    public ResponseEntity<BrandDTO> findById(@PathVariable Long id){
        return ResponseEntity.ok(brandService.findById(id));
    }

    @GetMapping("/of/category")
    public ResponseEntity<List<BrandDTO>> findByCategoryId(@RequestParam("id") Long id){
        return ResponseEntity.ok(brandService.findByCategoryId(id));
    }

    @GetMapping("/list")
    public ResponseEntity<List<BrandDTO>> findBrandsByIds(@RequestParam("ids") List<Long> ids){
        return ResponseEntity.ok(brandService.findByIds(ids));
    }
}
